package com.dxp.operation.controller;

import com.dxp.operation.core.Operation;
import com.dxp.operation.domain.User;
import com.dxp.operation.core.Log;
import com.dxp.operation.core.Module;
import com.dxp.operation.core.OperationLogContextHolder;
import com.dxp.operation.vo.respose.base.DefaultResult;
import com.dxp.operation.vo.respose.base.Result;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;


/**
 * 用户操作累，伪代码
 *
 * @author gaohui
 */
@RestController
@RequestMapping("v1/base/users")
public class UserController {

    private final Random random = new Random(System.currentTimeMillis());

    @Log(module = Module.BASE, operation = Operation.QUERY)
    @GetMapping
    public Result<List<User>> findAll(String username) {
        List<User> list = new ArrayList<>();
        list.add(new User(1L, "username-1", 25, 1));
        list.add(new User(2L, "username-2", 25, 2));
        list.add(new User(3L, "username-3", 29, 3));
        list.add(new User(4L, "username-4", 28, 5));
        list.add(new User(5L, "username-5", 27, 6));
        list.add(new User(6L, "username-6", 26, 7));
        OperationLogContextHolder.get().setRemark("6");
        return Result.suc(list);
    }

    @Log(module = Module.BASE, operation = Operation.SAVE)
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Result<User> save(@RequestBody User user) {
        user.setId(random.nextLong());
        return Result.suc(user);
    }

    @Log(module = Module.BASE, operation = Operation.UPDATE)
    @PutMapping
    public Result<User> update(@RequestBody User user) {
        OperationLogContextHolder.get().setRemark("自定义日志消息内容");
        return Result.suc(user);
    }

    @Log(module = Module.BASE, operation = Operation.DELETE)
    @DeleteMapping(value = "{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public Result<Object> delete(@PathVariable Long id) {
        return DefaultResult.suc();
    }

    @Log(module = Module.BASE, operation = Operation.UPLOAD)
    @PutMapping("file")
    public void upload(MultipartFile file) {
        String remark = String.format("文件名：%s, 大小： %s", file.getOriginalFilename(), file.getSize());
        OperationLogContextHolder.get().setRemark(remark);
    }

    /**
     * 测试失败情况
     *
     * @param id
     * @param name
     */
    @Log(module = Module.BASE, operation = Operation.UNKNOWN)
    @PostMapping("test")
    public Result<Object> test(Long id, String name) throws Exception {
        throw new Exception("错误");
    }

}
